package br.ucb.sirad.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.ucb.sirad.beans.Categoria;

public class CategoriaDAO extends DAO<Categoria>{
	
	private EntityManager em;
	
	public CategoriaDAO() {
		super(Categoria.class);
	}
	
	public List<Categoria> pesquisarPorNomePaginado(String nome,int firstResult, int maxResults){
		EntityManager em = new JPAUtil().getEntityManager();
		em.getTransaction().begin();
		
		Query query = em.createQuery("from "+Categoria.class.getName()+" where nome like :nome")
						.setParameter("nome", "%"+nome+"%");
		

		query = query.setFirstResult(firstResult).setMaxResults(maxResults);
				
		List<Categoria> lista = query.getResultList();
		em.getTransaction().commit();
		em.close();

		return lista;
	}
	
	public List<Categoria> buscarArvore(){

		EntityManager em = new JPAUtil().getEntityManager();
		em.getTransaction().begin();
		
		Query query = em.createQuery("from "+Categoria.class.getName()+" order by nome");
				
		List<Categoria> lista = query.getResultList();
		em.getTransaction().commit();
		em.close();

		return lista;
	}
	
	
	public int contaPorPesquisa(String chave) {
		EntityManager em = new JPAUtil().getEntityManager();
		
		long result = (Long) em.createQuery("select count(n) from " + Categoria.class.getName() + " n where nome like :nome")
				.setParameter("nome", "%"+chave+"%").getSingleResult();
		em.close();
		
		return (int) result;
	}
	
	public void removerDocumentoAssociado(){
		
	}
}
